/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>Project: javaweb - UpFile
 * <p>Powered by webrx On 2022-03-14 09:05:46
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebServlet("/upfile")
public class UpFile extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ParamDto p = parseParam(req);
        String user = p.getParamMap().get("user");
        System.out.println(user);

        FileItem file = p.getFileMap().get("fs");
        System.out.println(file.getName());
        System.out.println(file.getSize());
        System.out.println(file.getContentType());
        try {
            file.write(new File("c:/", file.getName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //处理上传多文件
        /*
        if(p.getFiles().size()>0){
            p.getFiles().forEach(item->{
                try {
                    item.write(new File("c:/", item.getName()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }*/
    }

    protected void abc(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //enctype="multipart/form-data" post
        if (ServletFileUpload.isMultipartContent(req)) {
            System.out.println("有文件上传");
            ServletFileUpload su = new ServletFileUpload(new DiskFileItemFactory());
            su.setHeaderEncoding("utf-8");
            try {
                List<FileItem> list = su.parseRequest(req);
                for (FileItem i : list) {
                    //判断是不是表单
                    if (i.isFormField()) {
                        //处理上传的表单
                        System.out.println(i.getFieldName());
                        System.out.println(i.getString("utf-8"));
                    } else {
                        //处理上传的文件
                        System.out.println("文件：");
                        System.out.println(i.getFieldName());
                        System.out.println(i.getName());
                        System.out.println(i.getSize());
                    }
                    System.out.println("----------------------");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            System.out.println("没有文件上传");
        }
    }

    /**
     * 从request流中解析参数与上传的文件
     *
     * @param request
     */
    public static ParamDto parseParam(HttpServletRequest request) {

        ParamDto result = new ParamDto();

        //创建一个FileItem工厂 通过DiskFileItemFactory对象创建文件上传核心组件
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        upload.setHeaderEncoding("UTF-8");

        try {
            //通过文件上传核心组件解析request请求，获取到所有的FileItem对象
            List<FileItem> fileItemList = upload.parseRequest(request);

            //遍历表单的所有表单项（FileItem） 并对其进行相关操作
            for (FileItem fileItem : fileItemList) {
                //判断这个表单项如果是一个普通的表单项
                if (fileItem.isFormField()) {
                    result.getParamMap().put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                    //如果不是表单的普通文本域，就是
                } else {
                    result.getFileMap().put(fileItem.getFieldName(), fileItem);
                    if (fileItem.getSize() > 0) {
                        result.getFiles().add(fileItem);
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
